package cn.stronglink.assetmanage.business.search.view.AssisChange;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import java.util.List;

import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.MainActivity;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.model.CheckDetailModel;
import cn.stronglink.assetmanage.business.check.presenter.CheckDetailPresenter;
import cn.stronglink.assetmanage.business.check.view.detail.CheckDetailView;
import cn.stronglink.assetmanage.business.inventory.model.InventoryDetailModel;
import cn.stronglink.assetmanage.business.inventory.view.detail.InventoryDetailFragment;
import cn.stronglink.assetmanage.business.search.model.AssisChangeModel;
import cn.stronglink.assetmanage.business.search.presenter.AssisChangePresenter;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Brand;
import cn.stronglink.assetmanage.entity.Department;
import cn.stronglink.assetmanage.entity.Model;
import cn.stronglink.assetmanage.entity.Node;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.assetmanage.widget.MenuOrderDialog;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * Created by zhengjinglan on 2018/6/19.
 */

public class AssisChangeFragment extends Fragment implements IAssetDetailView,View.OnClickListener{
    private TextView tv_asset_name;
    private Spinner sp_room;
    private EditText tv_asset_no;
    private Spinner sp_brand;
    private Spinner sp_type;
    private Spinner sp_model;
    private EditText tv_sn_no;
    private EditText tv_rfid_no;
    private TimerInfraraedScaner scaner;
    private AssisChangePresenter assisChangePresenter;
    private String roomId = "", typeId = "", brandId = "", modelId = "",userId="";
    private ArrayAdapter<Model> modelArrayAdapter;
    private SearchAsset searchAsset;
    private View view;
    private int PICTURE_URL = 1000;
    private ImageView iv_check_picture;
    private TextView textView;
    private TextView tv_manage_branch,tv_use_department;
    private Spinner sp_user;
    private MenuOrderDialog menuOrderDialog;
    private Node mNode;
    private Dialog mDialog;
    private TextView txt_title_right, txt_title_left, txt_main_title;
    private Bitmap bitmap;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_assis_change, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initData() {
        assisChangePresenter = new AssisChangePresenter(getContext(), this);
        Bundle bundle = getArguments();
        if (bundle != null) {
            String id = bundle.getString(Constants.CHECK_IN_DETAIL_NO);
            searchAsset = assisChangePresenter.getAssetDetail(id);
        }
        List<Type> typeList = assisChangePresenter.getTypeList();
        List<Brand> brandList = assisChangePresenter.getBrandList();
        List<Model> modelList = assisChangePresenter.getModelList();
        List<Room> roomList = assisChangePresenter.getRoomList();
        List<User> userList = assisChangePresenter.getUserList();
        ArrayAdapter<Type> typeArrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, typeList);
        ArrayAdapter<Brand> brandArrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, brandList);
        modelArrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, modelList);
        ArrayAdapter<Room> roomArrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, roomList);
        ArrayAdapter<User> userArrayAdapter = new ArrayAdapter<User>(getContext(),android.R.layout.simple_dropdown_item_1line,userList);
        sp_type.setAdapter(typeArrayAdapter);
        sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Type type = (Type) sp_type.getSelectedItem();
                typeId = type.getId_();
                assisChangePresenter.queryModelByBrandAndType();
                searchAsset.setTypeId_(typeId);
                searchAsset.setTypeName(type.getName());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_model.setAdapter(modelArrayAdapter);
        sp_model.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Model model = (Model) sp_model.getSelectedItem();
                modelId = model.getId_();
                searchAsset.setModelId_(modelId);
                searchAsset.setModelName(model.getName());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_brand.setAdapter(brandArrayAdapter);
        sp_brand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Brand brand = (Brand) sp_brand.getSelectedItem();
                brandId = brand.getId_();
                assisChangePresenter.queryModelByBrandAndType();
                searchAsset.setBrandId_(brandId);
                searchAsset.setBrandName(brand.getName());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_room.setAdapter(roomArrayAdapter);
        sp_room.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Room room = (Room) sp_room.getSelectedItem();
                roomId = room.getId_();
                searchAsset.setRoomId_(roomId);
                searchAsset.setRoomName(room.getName());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_user.setAdapter(userArrayAdapter);
        sp_user.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                userId = ((User)sp_user.getSelectedItem()).getId_();
                searchAsset.setEndUser(userId);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        // 初始化部门
        initBranch();
        // 显示
        if (searchAsset != null) {
            if (searchAsset.getAssetName() != null) {
                tv_asset_name.setText(searchAsset.getAssetName());
            }
            if (searchAsset.getAssetNo() != null) {
                tv_asset_no.setText(searchAsset.getAssetNo());
            }
            if (searchAsset.getSerialNo() != null) {
                tv_sn_no.setText(searchAsset.getSerialNo());
            }
            if (searchAsset.getRfidNo() != null) {
                tv_rfid_no.setText(searchAsset.getRfidNo());
            }
            if (searchAsset.getTypeName()!=null){
                setSpinnerItemSelectedByValue(sp_type,searchAsset.getTypeName());
            }
            if (searchAsset.getBrandName()!=null){
                setSpinnerItemSelectedByValue(sp_brand,searchAsset.getBrandName());
            }
            if (searchAsset.getModelName()!=null){
                setSpinnerItemSelectedByValue(sp_model,searchAsset.getModelName());
            }
            if (searchAsset.getRoomName()!=null){
                setSpinnerItemSelectedByValue(sp_room,searchAsset.getRoomName());
            }
            if (searchAsset.getManageBranchId_()!=null){
                String manageName = assisChangePresenter.getManageName(searchAsset.getManageBranchId_());
                tv_manage_branch.setText(manageName);
            }
            if (searchAsset.getUseBranchId_()!=null){
                String useBranchName = assisChangePresenter.getManageName(searchAsset.getUseBranchId_());
                tv_use_department.setText(useBranchName);
            }
            if (searchAsset.getEndUser()!=null){
                String userName = assisChangePresenter.getUserName(searchAsset.getEndUser());
                setSpinnerItemSelectedByValue(sp_user,userName);
            }
            if (searchAsset.getPictureUri()!=null){
                bitmap  = assisChangePresenter.getBitmap(searchAsset.getPictureUri());
                if (bitmap!=null){
                    iv_check_picture.setImageBitmap(bitmap);
                }
            }
        }
    }

    private void initView(final View view) {
        txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
        txt_title_right.setVisibility(View.VISIBLE);
        txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
        txt_title_left.setVisibility(View.VISIBLE);
        txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
        txt_main_title.setText("资产详情");
        txt_title_right.setText("保存");
        txt_title_right.setBackgroundDrawable(null);
        txt_title_right.setOnClickListener(this);
        tv_asset_name = view.findViewById(R.id.tv_asset_name);
        sp_room = view.findViewById(R.id.sp_room);
        tv_asset_no = view.findViewById(R.id.tv_asset_no);
        tv_asset_no.setOnClickListener(this);
        sp_brand = view.findViewById(R.id.sp_brand);
        sp_type = view.findViewById(R.id.sp_type);
        sp_model = view.findViewById(R.id.sp_model);
        tv_sn_no = view.findViewById(R.id.tv_sn_no);
        sp_user = view.findViewById(R.id.sp_user);
        tv_sn_no.setOnClickListener(this);
        tv_rfid_no = view.findViewById(R.id.tv_rfid_no);
        tv_rfid_no.setOnClickListener(this);
        iv_check_picture = view.findViewById(R.id.iv_check_picture);
        iv_check_picture.setOnClickListener(this);
        tv_manage_branch = view.findViewById(R.id.tv_manage_branch);
        tv_use_department = view.findViewById(R.id.tv_use_department);
        tv_manage_branch.setOnClickListener(this);
        tv_use_department.setOnClickListener(this);
        scaner = new TimerInfraraedScaner(getContext());
        scaner.setScanerListener(new IScanerListener() {
            @Override
            public void onScaning(List<String> data) {
                String value = data.get(data.size()-1).replace("\r","");
                textView.setText(value);
            }
        });
    }


    private void startActivityForPicture(int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //启动相机程序
        intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        AssisChangeFragment.this.startActivityForResult(intent, requestCode);
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (scaner!=null){
            scaner.stop();
            scaner.destory();
        }
    }

    @Override
    public void onUploadSuccess(SearchAsset searchAsset) {
        ToastUtil.toastShort("资产更新成功");
        AssisChangeFragment.this.getActivity().onBackPressed();
    }

    @Override
    public void onUploadFail(Exception e, final SearchAsset searchAsset) {
//        ToastUtil.toastShort("资产更新失败:"+e.getMessage());
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
                .setTitle("提示")
                .setMessage("资产上传失败:"+e.getMessage()+"，是否保存到本地？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        assisChangePresenter.saveToLocal(searchAsset);
                    }
                });
        builder.create().show();
    }

    @Override
    public void onSaveLocalSuccess(SearchAsset searchAsset) {
        ToastUtil.toastShort("数据已保存到本地成功");
        AssisChangeFragment.this.getActivity().onBackPressed();
    }

    @Override
    public void onSaveLocalFail(Exception e) {
        ToastUtil.toastShort("保存到本地失败:"+e.getMessage());
    }

    @Override
    public void showProgress(String msg) {
        mDialog = CustomProgressDialog.createLoadingDialog(getActivity(), msg);
        mDialog.setCancelable(false);
        mDialog.show();
    }

    @Override
    public void hideProgress() {
        if (mDialog!=null){
            mDialog.hide();
        }
    }

    @Override
    public String getTypeValue() {
        return typeId;
    }

    @Override
    public String getRoomValue() {
        return roomId;
    }

    @Override
    public String getSnValue() {
        return tv_sn_no.getText().toString();
    }

    @Override
    public String getRfidValue() {
        return tv_rfid_no.getText().toString();
    }

    @Override
    public String getBrandValue() {
        return brandId;
    }

    @Override
    public String getModelValue() {
        return modelId;
    }

    @Override
    public String getUserValue() {
        return userId;
    }

    @Override
    public Bitmap getCurrentBitmap() {
        return bitmap;
    }

    @Override
    public void onQueryModelListSuccess(List<Model> modelList) {
        modelArrayAdapter.clear();
        modelArrayAdapter.addAll(modelList);
    }

    /**
     * 根据值, 设置spinner默认选中:
     * @param spinner
     * @param value
     */
    private void setSpinnerItemSelectedByValue(Spinner spinner,String value){
        if (value==null)return;
        SpinnerAdapter apsAdapter= spinner.getAdapter(); //得到SpinnerAdapter对象
        int k= apsAdapter.getCount();
        for(int i=0;i<k;i++){
            if(value.equals(apsAdapter.getItem(i).toString())){
                spinner.setSelection(i,true);// 默认选中项
                break;
            }
        }
    }

   private void  initBranch(){
        InventoryDetailModel inventoryDetailModel = new InventoryDetailModel();
        MenuOrderDialog.Builder builder = new MenuOrderDialog.Builder(getContext());
        final List<Department> departmentList = inventoryDetailModel.getDepartment();
        builder.setDatas(departmentList);
        builder.setTitle("部门");
        builder.setNegativeButton("", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                menuOrderDialog.dismiss();
            }
        });
        builder.setPositiveButton("", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                menuOrderDialog.dismiss();
                if (mNode != null) {
                    if (textView == tv_manage_branch) {

                        tv_manage_branch.setText(mNode.getName());
                        searchAsset.setManageBranchId_(mNode.getId());

                    } else if (textView == tv_use_department) {
                        tv_use_department.setText(mNode.getName());
                        searchAsset.setUseBranchId_(mNode.getId());
                    }
                }
            }
        });
        menuOrderDialog =  builder.create();
        menuOrderDialog.setItemClickListener(new MenuOrderDialog.onItemClickListener() {
            @Override
            public void onItemClick(Node node, int position) {
                mNode = node;
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_check_picture:
                startActivityForPicture(PICTURE_URL);
                break;
            case R.id.tv_sn_no:
                textView = tv_sn_no;
                scaner.playSingle();
                break;
            case R.id.tv_rfid_no:
                textView = tv_rfid_no;
                scaner.playSingle();
                break;
            case R.id.tv_asset_no:
                textView = tv_asset_no;
                scaner.playSingle();
                break;
            case R.id.tv_manage_branch:
                if (menuOrderDialog!=null) {
                    textView = tv_manage_branch;
                    menuOrderDialog.show();
                }
                break;
            case R.id.tv_use_department:
                if (menuOrderDialog!=null) {
                    textView = tv_use_department;
                    menuOrderDialog.show();
                }
                break;

            case R.id.txt_right_title:
                searchAsset.setAssetNo(tv_asset_no.getText().toString());
                searchAsset.setSerialNo(tv_sn_no.getText().toString());
                searchAsset.setRfidNo(tv_rfid_no.getText().toString());
                assisChangePresenter.save(searchAsset);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                switch (requestCode) {
                    case 1000:
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
                            if (bitmap != null) {
                                iv_check_picture.setImageBitmap(bitmap);
                            }
                        }
                        break;
                }

                break;
            case RESULT_CANCELED:

                break;
        }
    }
}